﻿using DeviceFaultPushService.MessagePushService.Models;
using DeviceFaultPushService.SystemService.Model;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace DeviceFaultPushService.SystemService;

/// <summary>
/// 获取配置
/// </summary>
public static class GetConfiguration
{
    /// <summary>
    /// 系统配置
    /// </summary>
    public static SystemConfigurationModel Configuration { get; private set; }

    /// <summary>
    /// 获取配置文件
    /// </summary>
    public static void GetSettings(bool isRecursion = false)
    {
        string str = "";
        //检查是否是递归调用
        if (isRecursion == false)
        {
            str = GetGlobalSettings();
        }
        try
        {
            if (str.Length < 10)
            {
                //配置获取失败加载默认数据
                Configuration = new()
                {
                    AlarmInterval = 30,
                    CollectionInterval = 3,
                    EnablePushService = false,
                    EnableVoiceBroadcastingService = false,
                    Passageway = MessageChannelEnum.Null,
                    Template = "设备报警通知\t\n设备：name\t\n时间：date\t\n级别：level\t\n信息：information\t\n",
                };
            }
            else
            {
                //系列化配置文件
                Configuration = JsonSerializer.Deserialize<SystemConfigurationModel>(str);
            }
        }
        catch (Exception)
        {
            //递归调用
            GetSettings(true);
        }
    }

    /// <summary>
    /// 获取全局配置文件
    /// </summary>
    /// <returns></returns>
    private static string GetGlobalSettings()
    {
        if (File.Exists("Settings.json"))
        {
            return File.ReadAllText("Settings.json");
        }
        return "";
    }

    /// <summary>
    /// 配置文件写入
    /// </summary>
    /// <param name="configuration"></param>
    public static void WriteConfiguration(SystemConfigurationModel configuration)
    {
        string jsonString = JsonSerializer.Serialize(configuration, new JsonSerializerOptions()
        {
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        });

        File.WriteAllText("Settings.json", jsonString);
    }
}